package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.AliOssUtil;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 新增菜品默认状态为停售
        dish.setStatus(StatusConstant.DISABLE);

        dishMapper.inert(dish);
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });

            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品信息分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     * @param isUpdate true:修改菜品信息，false：起售停售菜品
     */
    @Transactional
    public void update(DishDTO dishDTO, boolean isUpdate) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 更新菜品信息
        dishMapper.update(dish);

        // 若不是起售停售菜品
        if(isUpdate) {
            Long dishId = dishDTO.getId();

            // 先删除菜品对应的口味
            dishFlavorMapper.deleteByDishId(dishId);

            // 再插入菜品对应的口味
            List<DishFlavor> flavors = dishDTO.getFlavors();
            if (flavors != null && flavors.size() > 0) {
                flavors.forEach(dishFlavor -> {
                    dishFlavor.setDishId(dishDTO.getId());
                });
                dishFlavorMapper.insertBatch(dishDTO.getFlavors());
            }
        }
    }

    /**
     * 根据id获取菜品信息
     * @param id
     * @return
     */
    public DishVO getById(Long id) {
        // 获取菜品基本信息
        Dish dish = dishMapper.getById(id);

        // 获取菜品对应的口味
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 删除菜品信息
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 判断要删除的菜品中是否存在起售的菜品
        List<Dish> dishes = dishMapper.getByIds(ids);
        for(Dish dish : dishes){
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 判断要删除的菜品中是否关联套餐
        List<SetmealDish> setmealDishes = setmealDishMapper.getByDishIds(ids);
        if(setmealDishes != null && setmealDishes.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        // 删除菜品信息
        dishMapper.deleteBatch(ids);

        // 删除菜品对应的口味
        dishFlavorMapper.deleteByDishIds(ids);

        // 删除菜品对应的图片（阿里云oss）
        List<String> objectNames = new ArrayList<>();
        for(Dish dish : dishes){
            String filePath = dish.getImage();
            // https://BucketName.Endpoint/ObjectName
            String objectName = filePath.substring(filePath.lastIndexOf("/") + 1);
            objectNames.add(objectName);
        }
        aliOssUtil.delete(objectNames);
    }


    /**
     * 根据菜品分类id获取菜品信息列表
     * @param categoryId
     * @return
     */
    public List<Dish> getByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId);

        return dishList;
    }

    /**
     * 根据菜品名称获取菜品信息列表
     * @param name
     * @return
     */
    public List<Dish> getByName(String name) {
        List<Dish> dishList = dishMapper.getByName(name);

        return dishList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
